<template>
  <div class="container" >
    <get-user-info v-if="isGetUserInfo" pageType="detail"  @updateUserInfo="initMemberInfo"></get-user-info>
    <!-- 头部自定义的返回按钮 -->
    <div class="top-nav" :style="'height: '+ spaceBarHeight + 'px; padding-top: '+ statusBarTop + 'px;'">
      <div class="flex-center v-align-c">
        <div
          :style="'width: '+ (spaceBarHeight - statusBarTop) + 'px; height: '+ (spaceBarHeight - statusBarTop - 10) + 'px;'"
          class="self-back flex flex-center"
          @click="goBackPage">
          <van-icon name="arrow" class="font-color-white" size="22px"/>
        </div>
        <div
          :style="'width: '+ (spaceBarHeight - statusBarTop)/2 + 'px; height: '+ (spaceBarHeight - statusBarTop - 10) + 'px;'"
          class="self-back flex flex-center"
          @click="goBackPage">
        </div>
        <div class="flex-item"></div>
      </div>
    </div>
    <!-- 微信分享按钮 -->
    <div class="wx-share-box width-30 height-30" :style="{position: 'fixed', top: btnInfo.top + 'px', left: btnInfo.left - 35 + 'px'}">
      <div class="flex-center flex">
        <img class="width-22 height-19" v-if="fileSpace" :src="fileSpace + '/images/wechat-icon.png'" alt="">
        <button open-type="share" class="share-btn width-30 height-30"></button>
      </div>
    </div>
    <!-- 头部自定义 搜索导航 -->
    <div ref="selfNav" class="self-nav pad-l-10 pad-r-10  pad-b-6" :style="{paddingTop: btnInfo.top + 'px',height: domSelfNavHeight + 'px'}" v-if="showSearchNav">
      <div class="flex v-align-c pad-b-10">
        <div @click="goBackPage">
          <van-icon name="arrow-left" size="24px" color="#333" />
        </div>
        <div @click="$pt.navigateTo({url: '/pages/home/search-view/main'})">
          <div class="width-200 height-32 search-box flex v-align-c pad-l-10">
            <van-icon name="search" size="20px"/>
            <span class="font-12 font-color-6 mar-l-7">搜索商品</span>
          </div>
        </div>
      </div>
      <div class="self-tab">
        <ul class="flex text-align-c">
          <li v-for="(item, index) of targetTabs" :key="index" class="flex-item" :class="index === targetIndex ? 'active-tab' : ''" @click="goTarget(index)">
            <span :style="{borderBottom: index === targetIndex? '2px solid #7427FF' : ''}">{{item}}</span>
          </li>
        </ul>
      </div>
    </div>
    <!-- 商品图片 (商品图轮播) -->
    <div ref="top" class="goods-detail-swiper">
      <swiper class="top-swiper" autoplay="true" interval="5000" indicator-color="rgba(255, 255, 255, 0.5)" indicator-active-color="#7427FF"
        duration="1000" indicator-dots="true">
        <template v-if="goods.goodsImages">
          <block v-for="(item, index) in goods.goodsImages" :key="index">
            <swiper-item>
              <img v-if="item" class="top-img" mode="aspectFill" :src="item.imageUrl + '?imageView2/2/w/600'" @click="previewImage(item, imgList)"/>
            </swiper-item>
          </block>
        </template>
      </swiper>
    </div>
    <!-- 商品信息： 价格 标题 商品卖点 -->
    <div class="goods-info-box pad-b-18" :style="{marginTop: 1 ? '-10px' : ''}">
      <!-- 价格 -->
      <div class="goods-price-info flex pad-t-16 pad-b-12" v-if="userStatus">
        <div class="pre-price flex-col flex-center">
          <span class="font-12">￥<span class="font-20" style="color:#fff">{{goods['anchorCommission']}}</span></span>
          <span>预计赚</span>
        </div>
        <div class="ratio flex-col flex-center">
          <span class="font-20">{{goods['anchorRatio']}}%</span>
          <span>佣金比例</span>
        </div>
        <div class="flex-col flex-center audience-price">
          <span class="font-12">￥<span class="font-20" v-text="goods['skuFlag'] === 1 ? goods['maxPrice'] : goods['sellPrice']"></span></span>
          <span>观众购买价</span>
          <div class="underline-price flex-center flex pad-l-4 pad-r-4" v-if="(goods['minScribingPrice'] && goods['minScribingPrice'] !== '0.00') || (goods['scribingPrice'] && goods['scribingPrice'] !== '0.00')">
            <span class="font-10" v-text="goods['skuFlag'] === 1 ? goods['minScribingPrice'] : goods['scribingPrice']"></span>
          </div>
        </div>
      </div>
      <div class="pad-t-20 font-16 pad-l-15 pad-r-15" v-else @click="goAnchor">
        <span class="remind-text font-w">成为主播后可见价格</span>
      </div>
      <div class="pad-l-15 pad-r-15">
        <!-- 等级佣金详情 -->
        <div v-if="goods.isShowAnchorOnePartnerCommission" class="income-bar flex flex-between pad-l-12 mar-b--3 mar-t-10">
          <span class="font-13 pad-t-3 pad-b-3">佣金详情</span>
          <div class="flex v-align-c pad-l-15 pad-r-2 pad-t-3 pad-b-3" @click="incomeDetail">
            <span class="font-12 pad-r-2">查看</span>
            <van-icon name="arrow" size="14px"/>
          </div>
        </div>
        <!-- 标题-->
        <div class="goods-title-info mar-t-10 ">
          <span class="font-16 font-w text-align-j">{{goods['title']}}</span>
        </div>
        <!-- 卖点 -->
        <div class="other-text mar-t-10">
          <span class="font-12">{{goods['sellPoint']}}</span>
        </div>
        <!-- 销售信息 -->
        <div class="font-12 font-color-9 flex flex-between mar-t-24">
          <div class="flex">
            <span>
              已售{{ goods.salesNum }}
              <label v-for="(item, index) in listGoodsUnitType" :key="index">
                <label>{{ goods.unitType === item.value ? item.text : '' }}</label>
              </label>
            </span>
            <span class="font-color-9 mar-l-10 mar-r-10">|</span>
            <span>{{inStockNum}}位网红在卖</span>
          </div>
          <span>
            库存{{ goodsStock }}
            <label v-for="(item, index) in listGoodsUnitType" :key="index">
              <label>{{ goods.unitType === item.value ? item.text : '' }}</label>
            </label>
          </span>
        </div>
      </div>
    </div>
    <!-- 直播商品链接 -->
    <div class="pad-l-15 pad-r-15 pad-t-20 pad-b-18 border-b-10" v-if="goods['anchorPlatformShopType'] || (goods['tiktokAuthority'] && goods['tiktokGoodsUrl']) || (goods['quickAuthority'] && goods['quickGoodsUrl']) || (goods['taobaoAuthority'] && goods['taobaoGoodsUrl'])">
      <p
        v-if="getRoleType !== 2"
        class="font-13 font-color-9">直播商品链接<span class="font-11 font-red">(复制链接到直播平台里挂载购物车)</span></p>
      <p
        v-else
        class="font-13 font-color-9">支持渠道</p>
      <div class="platform">
        <!-- 微信 -->
        <div class="wx-platform flex flex-between mar-t-24" v-if="goods['anchorPlatformShopType']">
          <div class="flex flex-center">
            <div class="width-20 height-20 flex flex-center icon-box">
              <img v-if="fileSpace" class="width-15 height-15" :src="fileSpace + '/images/anchor-wx-icon.png'" alt="" >
            </div>
            <span class="font-13 font-color-3 mar-l-7">小程序直播</span>
          </div>
          <span v-if="getRoleType !== 2" class="font-11" @click="goWxLive">立即带货</span>
        </div>
        <!-- 抖音 -->
        <div class="dy-platform flex flex-between mar-t-18" v-if="goods['tiktokAuthority']">
          <div class="flex flex-center">
            <div class="width-20 height-20 flex flex-center icon-box">
              <img v-if="fileSpace" class="width-15 height-15" :src="fileSpace + '/images/dy-icon.png'" alt="" >
            </div>
            <span class="font-13 font-color-3 mar-l-7">抖音</span>
          </div>
          <span v-if="getRoleType !== 2 && goods['tiktokGoodsUrl']" class="font-11" @click="copyLink(goods['tiktokGoodsUrl'])">复制链接</span>
        </div>
        <!-- 快手 -->
        <div class="ks-platform flex flex-between mar-t-18" v-if="goods['quickAuthority']">
          <div class="flex flex-center">
            <div class="width-20 height-20 flex flex-center icon-box">
              <img v-if="fileSpace" class="width-15 height-15" :src="fileSpace + '/images/ks-icon.png'" alt="">
            </div>
            <span class="font-13 font-color-3 mar-l-7">快手</span>
          </div>
          <span v-if="getRoleType !== 2 && goods['quickGoodsUrl']" class="font-11" @click="copyLink(goods['quickGoodsUrl'])">复制链接</span>
        </div>
        <!-- 淘宝 -->
        <div class="tb-platform flex flex-between mar-t-18" v-if="goods['taobaoAuthority']">
          <div class="flex flex-center">
            <div class="width-20 height-20 flex flex-center icon-box">
              <img v-if="fileSpace" class="width-15 height-15" :src="fileSpace + '/images/tb-icon.png'" alt="">
            </div>
            <span class="font-13 font-color-3 mar-l-7">淘宝</span>
          </div>
          <span v-if="getRoleType !== 2 && goods['taobaoGoodsUrl']" class="font-11" @click="copyLink(goods['taobaoGoodsUrl'])">复制链接</span>
        </div>
      </div>
    </div>
    <!-- 发货等参数设置 -->
    <div class="pad-l-15 pad-r-15 font-13 pad-t-20 pad-b-20">
      <div class="flex flex-between" @click="goPostFeeTemplate(goods.postFeeType, goods.deliveryTemplateId)">
        <div class="flex-item flex">
          <span class="font-color-9">发货</span>
          <span class="mar-l-20">{{goodsOtherInfo.prov}} {{goodsOtherInfo.city}}</span>
          <div v-if="goods.postFeeType!==10" class="mar-l-20">
            <span>运费:{{billingType}}</span>
            <span></span>
          </div>
          <div v-else class="mar-l-20">
            统一运费{{goods.postFee}}
          </div>
        </div>
        <van-icon name="arrow" v-if="goods.postFeeType!==10"/>
      </div>
      <div class="flex flex-between mar-t-12" @click="actionSheet(true)" v-if="goodsOtherInfo.goodsSafeguards.length">
        <div class="flex-item v-align-c">
          <span class="font-color-9">保障</span>
          <span class="mar-l-20 re-line-1">{{goodsOtherInfo.goodsSafeguardsStr}}</span>
        </div>
        <van-icon name="arrow" />
      </div>
      <div class="flex flex-between mar-t-12" @click="actionSheet(false)" v-if="goodsOtherInfo.goodsParameters.length">
        <div class="flex-item v-align-c">
          <span class="font-color-9">参数</span>
          <span class="mar-l-20 re-line-1">{{goodsOtherInfo.goodsParametersStr}}</span>
        </div>
        <van-icon name="arrow" />
      </div>
    </div>
    <!-- 助播素材 商品详情 tab -->
    <div class="pad-t-8 pad-b-8 cart-tab" id="area1">
      <div class="cart-tab-bar pad-b-11">
        <van-tabs :active="activeIndex" type="card" color="#333" @change="changeActiveTab">
          <van-tab :title="item" v-for="(item, index) in statusList" :key="index"></van-tab>
        </van-tabs>
      </div>
      <!-- 下载素材按钮 -->
      <van-sticky :offset-top="domSelfNavHeight + btnInfo.top" v-if="!activeIndex">
        <div class="pad-l-15 pad-r-15 height-43 mar-b-6 align-r v-align-c bg-color-white" @click="downLoad">
          <img v-if="fileSpace" :src="fileSpace + '/images/anchor-download-icon.png'" alt="" class="width-15 height-15">
          <span class="font-15 font-color-3 mar-l-5">下载素材</span>
        </div>
      </van-sticky>
      <div v-if="activeIndex === 0 && getCustomerId">
        <div v-for="(item, index) of goodsOtherInfo.anchorTemplateImgList" :key="index" :style="{padding: item.upperLowerMargins+'px '+ item.sideMargin+'px'}">
          <img :src="item.img + '?imageView2/2/w/600'" alt="" mode="widthFix" style="width:100%;height:100%" @click="previewImage(item, [item.img])">{{item.height}}
        </div>
        <div class="flex-center flex-col mar-t-20">
          <span class="font-14 mar-t-10 font-light-gray">长按或扫描查看商品详情</span>
          <span class="font-14 font-light-gray">一键上架商品</span>
        </div>
      </div>
      <div v-if="activeIndex === 1">
        <div class="align-c">
          <show-rich-text :fromGoodsId="goods.goodsId" :content="goodsOtherInfo.detailTemplateList" type="shopDetail"></show-rich-text>
        </div>
      </div>
    </div>
    <!-- 底部导航栏 -->
    <div>
      <div v-if="userStatus" class="flex bottom-btn">
        <div class="item-bottom flex">
          <ul class="flex">
            <li @click="$pt.reLaunch({ url: '/pages/home/main'})">
              <div>
                <img v-if="fileSpace" :src="fileSpace + '/images/anchor-home.png'" alt="" class="icon width-23 height-23" mode="widthFix">
              </div>
              <div class="item-b-txt">首页</div>
            </li>
            <li class="pos-rel" @click="$pt.reLaunch({ url: '/pages/shop/cart/main'})">
              <div>
                <img v-if="fileSpace" :src="fileSpace + '/images/anchor-list.png'" alt="" class="icon width-23 height-23" mode="widthFix">
              </div>
              <div class="item-b-txt">寄样清单</div>
              <div class="badge">
                <cart-badge ref="cartBadge"></cart-badge>
              </div>
            </li>
          </ul>
          <div class="btn line-h-1" @click="showSkuPanle(false)" :class="btnStatus === 1 || btnStatus ===2 ? 'btn-active' : 'btn-disactive'">
            <span>{{btnText}}</span>
          </div>
        </div>
      </div>
      <!-- 申请主播按钮 -->
      <div
        v-if="!userStatus && getRoleType !== 2"
        class="apply-btn font-16 text-align-c pad-t-15 pad-b-15"
        @click="goAnchor">
        <span v-if="getShowBuyCard">成为主播后可见价格，立即申请</span>
      </div>
    </div>
    <!-- 弹窗 该功能及主播可用-->
    <div class="self-alert" v-if="showAlert">
      <div class="img-box">
        <img v-if="fileSpace" :src="fileSpace+'/images/warn-01.png'" alt="">
      </div>
      <div class="text-box mar-t-20">
        <span>该功能仅主播可用</span>
      </div>
    </div>
    <!-- 进入主播端二维码 -->
    <div v-if="showCodeAlert">
      <van-popup :show="showCodeAlert" round="true" lock-scroll="true" @click="showCodeAlert=false">
        <canvas-card :codeUrl="goodsOtherInfo.weChatAnchorUrl" ref="canvas"></canvas-card>
      </van-popup>
      <div class="save-img-btn font-14" @click="saveCodeImg">保存到相册</div>
      <div class="img-colse-btn width-35" @click="showCodeAlert=false">
        <img class="width-35 height-35 layer-close" v-if="fileSpace" mode="widthFix" @click="closeEls" :src="fileSpace + '/images/w-icon-close.png'"/>
      </div>
    </div>
    <!-- sku选择 -->
    <div v-if="loadinSkuComponent">
      <get-sku-buy ref="getSkuBuy" :goodsData="goods" :qty="qty" :room_id="room_id" @finished="getSkuBuyFinished"></get-sku-buy>
    </div>
    <!-- 上拉弹窗 -->
    <div class="sheet-box">
      <van-action-sheet :show="showActionSheet" :title="actionSheetTitle" @close="closeActiveSheet">
        <div class="pad-15">
          <div class="mar-b-30" v-if="actionSheetTitle === '保障说明'">
            <div class="flex-col mar-t-14" v-for="(item ,index) of goodsOtherInfo.goodsSafeguards" :key="index">
              <div class="v-align-c">
                <img class="width-14 height-14" v-if="fileSpace" :src="fileSpace+'/images/hook.png'" alt="">
                <span class="mar-l-5 font-13 font-color-3 font-w">{{item.safeguardName}}</span>
              </div>
              <div class="mar-l-20 font-13 font-color-3">{{item.safeguardValue}}</div>
            </div>
          </div>
          <div v-if="actionSheetTitle === '产品参数'">
            <div v-for="(item, index) of goodsOtherInfo.goodsParameters" :key="index" class="mar-b-30">
              <van-row>
                <van-col span="6" class="font-13 font-color-9">{{item.parameterName}}</van-col>
                <van-col span="18" class="font-13 font-color-3">{{item.parameterValue}}</van-col>
              </van-row>
            </div>
          </div>
          <div class="sure-btn" @click="showActionSheet=false">知道了</div>
        </div>
      </van-action-sheet>
    </div>
    <toast-layer v-if="toastShow" :toastContent="toastContent" :toastDesc="toastDesc" :toastType="toastType"></toast-layer>
    <identity-type v-if="anchorBoolean"></identity-type>
    <!-- 选择身份：主播、中介 -->
    <user-type v-if="userTypeBoolean" ref="loginLayer"></user-type>
  </div>
</template>

<script>
  import GetUserInfo from '@/components/GetUserInfo'
  import CartBadge from '../components/CartBadge'
  import ToastLayer from '@/components/ToastLayer'
  import CanvasCard from '../components/CanvasCard'
  import GetSkuBuy from '@/components/GetSkuBuy'
  import ShowRichText from '@/components/CustomRichText/ShowRichText'
  import identityType from '@/components/identityType'
  import UserType from '@/components/UserType'
  import { deliveryTemplate, getByEnterpriseId, checkIsLogin } from '@/api/common'
  import { getMemberInfo } from '@/api/home'
  import { getGoodsDetails, listGoodsUnitType } from '@/api/shop'
  import {getAnchorApplyList} from '@/api/personal'
  import { getAuth } from '@/api/login'
  import {
    setIsPerfectionInfo,
    setOpenId,
    setRoleType,
    setCustomerId,
    setPhone,
    setNickName,
    setEnterpriseId,
    setAnchorType,
    setShowBuyCard
  } from '@/utils/auth'
  export default {
    components: { GetUserInfo, CartBadge, CanvasCard, GetSkuBuy, ShowRichText, ToastLayer, identityType, UserType },
    data() {
      return {
        statusBarHeight: 0,
        spaceBarHeight: 0,
        statusBarTop: 0,
        backType: true,
        cartTabTop: 0, // "素材/详情"tab元素距离顶部距离
        statusList: ['助播素材', '商品详情'],
        activeIndex: 0, // "素材/详情"tab索引值
        btnInfo: '', // 胶囊按钮信息
        showSearchNav: false, // 是否显示自定义导航
        targetIndex: 0, // 头部自定义导航 tab索引值
        targetTabs: ['商品', '助播素材', '详情'],
        domSelfNavHeight: 70, // 下载素材按钮吸顶位置、头部自定义导航高度
        devHeight: 0, // 屏幕高度
        showAlert: false,
        showCodeAlert: false,
        loadinSkuComponent: false,
        listGoodsUnitType: [],
        qty: '',
        goods: {},
        room_id: '',
        showActionSheet: false, // 是否显示上拉弹窗
        actionSheetTitle: '',
        inStockNum: '', // 在售网红人数
        btnText: '', // 底部按钮文字
        btnStatus: 1, // 按钮状态
        goodsOtherInfo: {
          prov: '',
          city: '',
          anchorTemplateId: '',
          detailTemplateId: '',
          anchorTemplateImgList: [], // 素材图片集合
          detailTemplateList: [],
          goodsParametersStr: '', // 参数
          goodsSafeguardsStr: '', // 保障
          goodsParameters: [],
          goodsSafeguards: [],
          weChatAnchorUrl: '' // 主播二维码
        },
        billingType: '', // 运费计费类型
        downIndex: 0,
        detailsBoolean: false, // 商品详情素材
        userStatus: false, // 用于判断用户是否是主播身份
        toastShow: false,
        toastType: '',
        toastContent: '',
        toastDesc: '',
        isGetUserInfo: false,
        anchorBoolean: false,
        promptText: '',
        platformObj: {},
        statusNum: null,
        imgList: [],
        deliveryTemplateId: '', // 运费模版ID
        goodsStock: null,
        userTypeBoolean: false,
        authCustomerId: '',
        authPhone: '',
        authCustomerData: false,
        showSkuFlag: 0
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      this.spaceBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44
      this.statusBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44
      // 店铺信息栏
      this.statusBarTop = this.statusBarHeight - 38
      let sysInfo = ''
      sysInfo = this.$pt.getSystemInfoSync()
      if (sysInfo.system.indexOf('iOS') === -1) {
        // android类型
        this.statusBarTop = this.statusBarHeight - 37
        this.$pt.setStorageSync('iOS', false)
      } else {
        this.$pt.setStorageSync('iOS', true)
      }
      this.$pt.setStorageSync('devW', wx.getSystemInfoSync().windowWidth)
      // 获取胶囊按钮位置信息
      this.btnInfo = wx.getMenuButtonBoundingClientRect()
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    },
    onShareAppMessage() {
      // 分享
      return {
        title: this.goods.title,
        path: 'pages/shop/detail/main?memberId=' + this.getCustomerId + '&goodsId=' + this.goods.goodsId +
        '&goodsType=' + this.goods.goodsType,
        imageUrl: this.goods.goodsImages[0].imageUrl
      }
    },
    onShareTimeline() {
      return {
        title: this.goods.title,
        imageUrl: this.goods.goodsImages[0].imageUrl,
        query: 'memberId=' + this.getCustomerId + '&goodsId=' + this.goods.goodsId +
        '&goodsType=' + this.goods.goodsType
      }
    },
    onPageScroll(e) {
      // 滚动事件监听 (当滚到商品轮播图二分之一处触发操作)
      this.showSearchNav = e.scrollTop > 187
      if (!this.showSearchNav) this.targetIndex = 0
    },
    async onShow() {
      // 判断是否在预览sku图片
      // if (this.$store.state.previewImageFlag) {
      //   return
      // }
      this.show()
      if (this.$pt.getStorageSync('openId')) {
        await this.checkIsLogin(this.$pt.getStorageSync('openId'))
        if (this.authCustomerData && this.getRoleType !== 2) {
          await this.authAgainEls()
        }
      }
      if (this.$pt.getStorageSync('anchorBack')) {
        this.$pt.removeStorageSync('anchorBack')
        this.init()
      }
      // 小程序朋友圈分享
      if (wx.getLaunchOptionsSync().scene && wx.getLaunchOptionsSync().scene === 1154) {
        this.init()
      }
    },
    async mounted() {
      if (!this.$pt.getStorageSync('openId') || !this.$pt.getStorageSync('showBuyCard')) {
        await this.authEls()
      }
      await this.checkIsLogin(this.$pt.getStorageSync('openId'))
      if (this.authCustomerData && this.getRoleType !== 2) {
        await this.authAgainEls()
      }
      this.init()
    },
    methods: {
      incomeDetail() {
        if (!this.showSkuFlag) return
        this.$pt.navigateTo({ url: '/pages/shop/detail/income/main?goodsId=' + this.getCurrentPage().query.goodsId })
      },
      loginBackEls() {
        this.init()
      },
      authEls() {
        return new Promise((resolve, reject) => {
          let that = this
          this.$pt.login({
            success(res) {
              if (res.code) {
                getAuth(res.code).then((response) => {
                  if (response.data.openId) {
                    setOpenId(response.data.openId)
                  }
                  if (response.data.customerId) {
                    that.authCustomerId = response.data.customerId
                  }
                  if (response.data.phone) {
                    that.authPhone = response.data.phone
                  }
                  if (response.data.showBuyCard) {
                    setShowBuyCard(response.data.showBuyCard)
                  }
                  resolve(true)
                }).catch(() => {
                })
              }
            }
          })
        })
      },
      authAgainEls() {
        return new Promise((resolve, reject) => {
          this.$pt.login({
            success(res) {
              if (res.code) {
                getAuth(res.code).then((response) => {
                  if (response.data.customerId) {
                    setCustomerId(response.data.customerId)
                  }
                  if (response.data.showBuyCard) {
                    setShowBuyCard(response.data.showBuyCard)
                  }
                  resolve(true)
                }).catch(() => {
                })
              }
            }
          })
        })
      },
      nextTickLoginEls() {
        this.$nextTick(() => {
          this.$refs.loginLayer.selUser(2)
        })
      },
      checkIsLogin(openId) {
        return new Promise((resolve, reject) => {
          checkIsLogin({ openId: openId }).then((response) => {
            if (response.isError) return
            // response.code = 5001
            if (response.code === 5000 && this.getCustomerId) {
              setRoleType(1)
              this.$pt.setStorageSync('loginCode', response.code)
            }
            if (response.code === 5001) {
              this.$utils.showToast({ title: response.msg })
              this.userTypeBoolean = false
              setTimeout(() => {
                this.userTypeBoolean = true
                this.nextTickLoginEls()
              }, 100)
              setRoleType(2)
              this.$pt.setStorageSync('loginCode', response.code)
            }
            if (response.code === 101) {
              setRoleType(response.data.roleType)
              switch (response.data.roleType) {
                case 1:
                  // 主播身份
                  this.$pt.setStorageSync('loginCode', 1)
                  if (!response.data.customerMemberId && this.authCustomerId) {
                    setCustomerId(this.authCustomerId)
                  }
                  this.authCustomerData = false
                  if (!response.data.customerMemberId && !this.authCustomerId) {
                    this.authCustomerData = true
                  }
                  if (!response.data.customerMemberId && this.authPhone) {
                    setPhone(this.authPhone)
                  }
                  if (response.data.customerMemberId) {
                    setCustomerId(response.data.customerMemberId)
                  }
                  break
                case 2:
                  // 中介身份
                  setCustomerId(response.data.partnerId)
                  setPhone(response.data.phone)
                  if (response.data.partnerName) {
                    setNickName(response.data.partnerName)
                  }
                  if (response.data.enterpriseId) {
                    setEnterpriseId(response.data.enterpriseId)
                  }
                  setAnchorType(1)
                  this.$pt.setStorageSync('loginCode', 2)
                  break
              }
            }
            resolve(true)
          }).catch(() => {
          })
        })
      },
      // 会员基本信息
      initCustomerInfo() {
        if (this.getRoleType === 2) return
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          if (response.data.enterpriseId) {
            this.getByEnterpriseId(response.data.enterpriseId)
          }
        }).catch(() => {
        })
      },
      getByEnterpriseId(enterpriseId) {
        // 获取企业参数配置
        getByEnterpriseId({enterpriseId: enterpriseId}).then(response => {
          if (response.isError) return
          // response.data.isOpenAnchorCompulsoryPerfectionInfo = 0
          if (response.data.isOpenAnchorCompulsoryPerfectionInfo) {
            setIsPerfectionInfo(response.data.isOpenAnchorCompulsoryPerfectionInfo)
          } else {
            setIsPerfectionInfo(0)
          }
        }).catch({})
      },
      initMemberInfo() {
        this.getAnchorApplyList()
      },
      getAnchorApplyList() {
        if (!this.getCustomerId) return
        this.statusNum = null
        let data = {
          memberId: this.getCustomerId
        }
        getAnchorApplyList(data).then((response) => {
          if (response.isError) return
          let resData = response.data
          if (resData.length) {
            this.statusNum = -1
            resData.forEach(item => {
              this.$set(this.platformObj, item['relationPlatform'], {})
              this.$set(this.platformObj[item['relationPlatform']], 'applyStatus', item['applyStatus'])
              this.$set(this.platformObj[item['relationPlatform']], 'rejectReason', item['rejectReason'])
              if (item.applyStatus === 1) {
                this.statusNum = 1
              }
            })
          }
        }).catch(() => {
        })
      },
      goAnchor() {
        if (!this.getCustomerId) {
          if (!this.$pt.getStorageSync('roleType')) {
            this.userTypeBoolean = true
            return
          }
          this.isGetUserInfo = false
          setTimeout(() => {
            this.isGetUserInfo = true
          }, 100)
        } else {
          if (this.statusNum) {
            this.anchorBoolean = true
          } else {
            this.$pt.navigateTo({ url: '/pages/personal/apply-anchor/main?inPage=1' })
          }
        }
      },
      saveCodeImg() {
        this.$refs.canvas.saveToAlbum('qrCodeCanvas')
      },
      // 页面初始
      init() {
        this.userStatus = this.getCustomerId && this.$pt.getStorageSync('anchorType')
        this.detailsBoolean = false
        const that = this
        // 获取"素材/详情"tab元素距离顶部距离
        const query = wx.createSelectorQuery()
        query.select('#area1').boundingClientRect(function(rect) {
          that.cartTabTop = rect.top
        }).exec()
        // 获取当前屏幕高度
        this.devHeight = wx.getSystemInfoSync().windowHeight
        // 判断是否是主播 不是主播不显示助播素材内容
        if (!(this.getCustomerId && this.$pt.getStorageSync('anchorType'))) {
          this.activeIndex = 1
        }
        // 获取商品详情信息
        this.initUserGoods()
      },
      show() {
        this.detailsBoolean = false
        if (this.getCurrentPage().query.room_id) {
          this.room_id = this.getCurrentPage().query.room_id
        }
        this.initMemberInfo()
        this.initCustomerInfo()
      },
      // 前往运费模版信息页
      goPostFeeTemplate(type, templateId) {
        if (type === 10) return
        this.$pt.navigateTo({url: `/pages/shop/detail/courier-fee/main?deliveryTemplateId=${templateId}`})
      },
      initUserGoods() {
        this.$pt.showLoading({title: '加载中...'})
        let data = {
          goodsId: this.getCurrentPage().query.goodsId,
          customerId: this.getCustomerId,
          roleType: this.getRoleType ? this.getRoleType : ''
        }
        setTimeout(() => {
          this.$pt.hideLoading()
        }, 100)
        this.showSkuFlag = 0
        getGoodsDetails(data).then(response => {
          // console.log(response)
          // this.$pt.hideLoading()
          response.data.unitType = response.data.unitType ? response.data.unitType.toString() : '1'
          this.goods = response.data
          let _data = response.data
          // 已售数
          this.goods.salesNum = _data.salesNum > 10000 ? `${(_data.salesNum / 10000).toFixed(1)}w` : _data.salesNum
          // 库存
          this.goodsStock = _data.remainStock > 10000 ? `${(_data.remainStock / 10000).toFixed(1)}w` : _data.remainStock
          // 网红在卖数
          const _inStockNum = _data['putawayNum'] + _data['virtualPutawayNum']
          this.inStockNum = _inStockNum > 10000 ? `${(_inStockNum / 10000).toFixed(1)}w` : _inStockNum
          // 主播二维码
          this.$set(this.goodsOtherInfo, 'weChatAnchorUrl', _data.weChatAnchorUrl)
          // 获取图片地址列表 用于图片预览使用
          this.goods.goodsImages.forEach(item => {
            this.imgList.push(item.imageUrl)
          })
          // 商品发货 保障 参数等信息
          this.goodsOtherInfo.prov = _data['prov'] || ''
          this.goodsOtherInfo.city = _data['city'] || ''
          this.goodsOtherInfo.goodsSafeguards = _data.goodsSafeguards
          this.goodsOtherInfo.goodsParameters = _data.goodsParameters
          let _paramsArr = []
          let _safeguardsArr = []
          _data.goodsParameters.forEach((item) => {
            _paramsArr.push(item.parameterName)
          })
          this.goodsOtherInfo.goodsParametersStr = _paramsArr.join('•')
          _data.goodsSafeguards.forEach(item => {
            _safeguardsArr.push(item.safeguardName)
          })
          this.goodsOtherInfo.goodsSafeguardsStr = _safeguardsArr.join('•')
          // 获取商品运费 计费方式
          if (_data.postFeeType === 11) {
            this.deliveryTemplateId = _data.deliveryTemplateId
          }
          if (_data.postFeeType === 12) {
            this.deliveryTemplateId = _data.qualityTable[0]['deliveryTemplateId']
          }
          if (_data.postFeeType !== 10) {
            deliveryTemplate({templateId: this.deliveryTemplateId}).then(res => {
              switch (res.data.feeType) {
                case 1:
                  this.billingType = '按件计算'
                  break
                case 2:
                  this.billingType = '按重量计算'
                  break
                case 3:
                  this.billingType = '按体积计算'
                  break
              }
            })
          }
          // 获取助播素材 商品详情素材
          if ('anchorDetails' in _data) {
            let _templateImgArr = []
            _data['anchorDetails'].forEach(item => {
              _templateImgArr.push({img: item['src'], sideMargin: item['style']['sideMargin'], upperLowerMargins: item['style']['upperLowerMargins']})
            })
            this.$set(this.goodsOtherInfo, 'anchorTemplateImgList', _templateImgArr)
          }
          this.goodsOtherInfo.anchorTemplateImgList.push({img: _data.wxaCode})
          if ('details' in _data) {
            this.$set(this.goodsOtherInfo, 'detailTemplateList', _data['details'])
          }
          this.btnStatus = _data['anchorGoodsStatus']
          this.getBtnStatus(_data['anchorGoodsStatus'])
          // if (this.getRoleType === 2) {
          //   this.btnStatus = 2
          //   this.btnText = '免费领样'
          // }
          this.showSkuFlag = 1
          this.initListGoodsUnitType()
        }).catch(() => {
          // this.$pt.hideLoading()
        })
      },
      goBackPage() {
        if (this.getCurrentPage().query['memberId']) {
          this.$pt.reLaunch({url: '/pages/home/main'})
        } else {
          let that = this
          this.$pt.navigateBack({
            delta: -1,
            fail(res) {
              that.$pt.reLaunch({url: '/pages/home/main'})
            }
          })
        }
      },
      // 获取底部按钮状态(禁用/免费寄样/成本价买样)
      getBtnStatus(anchorGoodsStatus) {
        if (!anchorGoodsStatus) return
        // 1.判断商品状态(商品状态 1：正常 2：免费寄样 3：已加入寄样清单 4：已购样品 5：商品已售罄)
        switch (anchorGoodsStatus) {
          case 1:
            this.btnText = '成本价买样'
            break
          case 2:
            this.btnText = '免费寄样'
            break
          case 3:
            this.btnText = '已加入寄样清单'
            break
          case 4:
            this.btnText = '已购样品'
            break
          case 5:
            this.btnText = '商品已售罄'
            break
        }
      },
      // 下载素材图片
      downLoad() {
        let that = this
        // that.goodsOtherInfo.anchorTemplateImgList.push({img: that.goods.wxaCode})
        // 获取用户授权的权限
        this.$pt.getSetting({
          success: res => {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              // 如果没有授权图片保存功能,则进行授权申请操作
              that.$pt.authorize({
                scope: 'scope.writePhotosAlbum',
                success: function(opres) {
                  // 授权图片保存功能成功
                  that.$utils.showToast({ title: '下载中请勿操作' })
                  // 调用保存图片函数
                  that.drawPage()
                },
                fail: function(res) {
                  that.toastShow = true
                  that.toastType = 'warm'
                  that.toastContent = '下载失败，请重新发起'
                }
              })
            } else {
              // 已经授权过图片保存功能的则，直接调用保存图片函数
              that.drawPage()
            }
          },
          fail: function(res) {
            that.toastShow = true
            that.toastType = 'warm'
            that.toastContent = '下载失败，请重新发起'
          }
        })
      },
      drawPage() {
        let that = this
        let arrData = that.goodsOtherInfo.anchorTemplateImgList
        if (this.downIndex < arrData.length) {
          this.$pt.downloadFile({
            url: arrData[that.downIndex].img + '?imageView2/1/w/700/h/700',
            success: (img) => {
            // 将图片保存到相册
              that.$pt.saveImageToPhotosAlbum({
                filePath: img.tempFilePath,
                success: (res) => {
                  that.downIndex++
                  that.toastShow = true
                  that.toastType = 'loading'
                  that.toastContent = '下载中请勿操作'
                  that.toastDesc = that.downIndex + '/' + arrData.length
                  return that.drawPage()
                },
                fail: function(err) {
                  that.toastShow = true
                  that.toastType = 'warm'
                  that.toastContent = '下载失败，请重新发起'
                  if (err.errMsg.indexOf('cancel') !== -1) return wx.hideLoading()
                  console.log(`第${that.downIndex + 1}张保存失败`)
                  return that.drawPage()
                }
              })
            },
            fail: function(res) {
              that.toastShow = true
              that.toastType = 'warm'
              that.toastContent = '下载失败，请重新发起'
            }
          })
        } else {
          this.downIndex = 0
          wx.hideLoading()
          setTimeout(() => {
            this.toastShow = true
            this.toastType = 'success'
            this.toastContent = '下载成功'
            this.toastDesc = '请查看手机相册'
          }, 800)
        }
      },
      getSkuBuyFinished(params) {
        this.$pt.setStorageSync('skuParams', params)
        this.$refs.cartBadge.initCount()
      },
      // 点击跳转到指定区域 (锚点定位)
      goTarget(index) {
        if (index === this.targetIndex) return
        if (this.getCustomerId && this.$pt.getStorageSync('anchorType')) {
          this.targetIndex = index
          let scrollTop = !index ? 0 : this.cartTabTop
          wx.pageScrollTo({
            scrollTop: scrollTop,
            duration: 300
          })
          if (index === 1) {
            this.activeIndex = 0
          }
          if (index === 2) {
            this.activeIndex = 1
          }
        } else {
          this.$utils.showToast({ title: '仅主播可见助播素材' })
          this.targetIndex = 2
          let scrollTop = this.cartTabTop
          wx.pageScrollTo({
            scrollTop: scrollTop,
            duration: 300
          })
          this.activeIndex = 1
        }
      },
      // 切换 "素材/详情" tab
      changeActiveTab(e) {
        let index = e.mp.detail.index
        if (this.getCustomerId && this.$pt.getStorageSync('anchorType')) {
          this.activeIndex = index
        } else {
          if (!index) {
            this.$utils.showToast({ title: '仅主播可见助播素材' })
            this.activeIndex = 1
          }
        }
        this.targetIndex = this.activeIndex + 1
      },
      httpString(s) {
        var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g
        s = s.match(reg)
        return s
      },
      // 复制链接
      copyLink(url) {
        if (this.getCustomerId && this.$pt.getStorageSync('anchorType') && url) {
          this.$pt.setClipboardData({data: url})
        } else {
          const that = this
          this.showAlert = true
          setTimeout(() => {
            that.showAlert = false
          }, 2500)
        }
      },
      // 小程序直播
      goWxLive() {
        if (this.userStatus) {
          this.showCodeAlert = true
        } else {
          const that = this
          this.showAlert = true
          setTimeout(() => {
            that.showAlert = false
          }, 2000)
        }
      },
      showSkuPanle(isCart) {
        if (!this.showSkuFlag) return
        if (this.btnStatus === 3 || this.btnStatus === 4 || this.btnStatus === 5) return
        const _that = this
        this.loadinSkuComponent = true
        this.$nextTick(() => {
          _that.$refs.getSkuBuy.showSkuPanle(isCart)
        })
      },
      // 价格单位
      initListGoodsUnitType() {
        listGoodsUnitType(this.getCustomerId).then((response) => {
          if (response.isError) return
          this.listGoodsUnitType = this.$utils.objToArr(response.data, ['text', 'value'])
          this.listGoodsUnitType.forEach(item => {
            if (this.goods.unitType === item.value) {
              this.qty = item.text
            }
          })
        }).catch(() => {
        })
      },
      actionSheet(bool) {
        this.showActionSheet = true
        this.actionSheetTitle = bool ? '保障说明' : '产品参数'
      },
      closeActiveSheet() {
        this.showActionSheet = false
      },
      previewImage(current, images) {
        this.$pt.previewImage({
          urls: images,
          current: current,
          success: res => {
            this.$store.commit('setPreviewImageFlag', true)
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.container{
  background: white;
  min-height: calc(100vh);
  padding-bottom: 55px;
  .top-nav{
    color: #ffffff;
    box-sizing: border-box;
    text-align: center;
    font-size: 15px;
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    .top-txt{
      font-size: 18px;
      color: #ffffff;
    }
    .self-back {
      transform: rotate(180deg);
    }
  }
  .self-nav {
    background: #fff;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 102;
    /deep/ .van-search {
      padding: 0;
    }
    .self-tab {
      ul {
        .active-tab {
          color: #7427FF;
        }
      }
    }
    .search-box {
      background: #f5f5f5;
      border-radius: 16px;
    }
  }
  .income-bar{
    background: #f2ebff;
    color: #7427FF;
    border-radius: 4px;
    /deep/ .van-icon-arrow{
      color: #7427FF;
    }
  }
  .wx-share-box {
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    position:absolute;
    z-index: 103;
    border-radius: 50%;
    &>div{
      position: relative;
      width: 100%;
      height: 100%;
    }
    .share-btn{
      position: absolute;
      top: 0;
      left: 0;
      z-index: 4;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0);
    }
    .share-btn::after{
      border: none !important;
    }
  }
  .goods-detail-swiper {
    position: relative;
  }
  .goods-info-box {
    position: relative;
    box-sizing: border-box;
    border-bottom: 10px solid #F5F5F5;
    .goods-price-info {
      color: #fdfdfd;
      background-image: linear-gradient(to right, #7427FF,#6550FF);
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      padding-left: 25px;
      padding-right: 50px;
      display: flex;
      justify-content: space-between;
      .audience-price {
        position: relative;
        .underline-price {
          position: absolute;
          color: #7427FF;
          height: 12px;
          background: rgba(255, 255, 255, 0.5);
          border-radius: 4px;
          top: -12rpx;
          right: -30px;
          text-decoration: line-through;
        }
        .underline-price::after{
          width: 0;
          height: 0;
          content: '';
          border-top: 5px solid #B2A7FF;
          border-right: 5px solid transparent;
          position: absolute;
          bottom: -5px;
          left: 9px;
          z-index: 0;
        }
      }
    }
    .remind-text {
      color: #FF3939;
    }
    .other-text {
      color: #999999;
    }
  }
  .apply-btn {
    background: #7427FF;
    color: #fff;
    width: 100%;
    position: fixed;
    bottom: 0;
    z-index: 2;
  }
  .platform {
    .dy-platform {
      .icon-box {
        border-radius: 4px;
        background: #000;
      }
    }
    .wx-platform {
      .icon-box {
        border-radius: 4px;
        background: #09BB07;
      }
    }
    .tb-platform {
      .icon-box {
        border-radius: 4px;
        background: #FC8848;
      }
    }
    .ks-platform {
      .icon-box{
        border-radius: 4px;
        background: #FA9401;
      }
    }
    &> div > span {
      border-radius: 3px;
      background: #F6F1FF;
      width: 58px;
      color: #5922BE;
      text-align: center;
      height: 18px;
      line-height: 18px;
    }
  }
}
.qr-code-canvas {
  width: 240px;
  height: 300px;
}
.save-img-btn {
  position:fixed;
  z-index:9999;
  color:#fff;
  width: 193px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 20px;
  background: #7427FF;
  left: 50%;
  margin-left: -193rpx;
  top: 1130rpx;
}
.img-colse-btn {
  position:fixed;
  z-index:9999;
  left: 50%;
  margin-left: -17.5px;
  top: 1230rpx;
}
.top-swiper {
  width: 375px;
  height: 375px;
}

.top-img {
  width: 375px;
  height: 375px;
}
.bottom-btn {
  width: 100%;
  height: 53px;
  position: fixed;
  bottom: 0;
  background-color: #fff;
  align-items: center;
  justify-content: center;
  box-shadow: 0px 0px 10px 5px #f2f2f2;
  z-index: 2;
  .item-bottom {
    width: 348px;
    height: 100%;
    justify-content: space-between;
    align-items: center;
    ul {
      display: flex;
      justify-content: space-around;
      margin-right: 14px;
    }
    .btn {
      width: 230px;
      overflow: hidden;
      height: 42px;
      line-height: 42px;
      border-radius: 100px;
      text-align: center;
    }
    .btn-active {
      background: #7427FF;
      color: #fff;
    }
    .btn-disactive {
      background: #E5E5E5;
      color: #666666;
    }
    ul {
      flex: 1;
      li {
        font-size: 11px;
        color: #333333;
        text-align: center;
        .icon {
          display: inline-block;
          margin: 0 auto;
        }
        .item-b-txt {
          display: block;
          margin-top: 4px;
          overflow: hidden;
        }
        .badge {
          position: absolute;
          right: 0;
          top: -3px;
          z-index: 101;
          zoom: 0.9;
        }
      }
      &>li:nth-child(2) {
        margin-left: 15px;
      }
    }
  }
}
.border-b-10 {
  border-bottom: 10px solid #f5f5f5;
}
.cart-tab {
  background: #F5F5F5;
  /deep/ .van-tabs__nav--card {
    border: 1px solid #333;
  }
}
.self-alert {
  position: fixed;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 10rpx;
  padding: 20rpx;
  color: #fff;
  left: 50%;
  top: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transform: all 0.3s;
  font-size: 28rpx;
  margin-top: -63px;
  margin-left: -63px;
  z-index: 2;
  .img-box {
    img{
      width: 140rpx;
      height: 140rpx;
    }
  }
  .text-box{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}
.sheet-box {
  /deep/ .sheet-index--van-action-sheet {
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
  }
  /deep/ .van-action-sheet__header {
    background: #FBF9FF;
  }
  .sure-btn {
    width: 345px;
    overflow: hidden;
    height: 42px;
    line-height: 42px;
    color: #fff;
    border-radius: 100px;
    text-align: center;
    background: #7427FF;
    position: relative;
    left: 50%;
    transform: translate(-172.5px, 0px);
  }

}
.re-line-1 {
  height: 20px;
  width: 80%;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-line-clamp:1;
  -webkit-box-orient:vertical;
  word-break:break-word;
}
</style>
